package server;

import com.mongodb.DBCollection;
import com.mongodb.DBObject;

import data.Data;
import data.MyCache;

public class Monitor extends Thread {
	long timeout;
	Thread[] group;
	DBObject domain;

	public Monitor(long timeout, Thread[] group, DBObject domain) {
		this.timeout = timeout;
		this.group = group;
		this.domain = domain;
		this.start();
	}

	public void run() {
		try {
			this.sleep(timeout);
			// Get a memcached client connected to several servers

			DBCollection collection = Data.data("domain");
			collection.save(domain);

			Object obj = MyCache.getInstance().get("last-update");

			if (obj == null) {
				String strDomain = domain.get("name").toString();
				MyCache.getInstance().set("last-update", 3600 * 24, strDomain);
			} else {
				String[] arrDomain = obj.toString().split(",");
				String strDomain = "";
				if (arrDomain.length > 12) {
					for (int i = 0; i < arrDomain.length; i++) {
						if (i != 0)
							strDomain += arrDomain[i] + ",";
					}
					strDomain += domain.get("name").toString();
				} else {
					strDomain = obj.toString() + "," + domain.get("name").toString();
				}

				MyCache.getInstance().set("last-update", 3600 * 24, strDomain);

			}
		} catch (InterruptedException e) {

			e.printStackTrace();
		} finally {
			for (int i = 0; i < group.length; i++) {
				try {
					group[i].suspend();
					group[i].stop();
				} catch (Exception e2) {
					// TODO: handle exception
				}
			}

		}

	}
}
